#include "Persistence.h"

#include <sstream>
#include "util/coding.h"

using namespace leveldb;

KeyValueParser::KeyValueParser(const Slice & bytes)
: bytes_(bytes)
{
}
KeyValueParser::~KeyValueParser(){}

bool KeyValueParser::key(uint64_t * key){
    if(leveldb::GetVarint64(&bytes_, key) == false){
        return false;
    }
    return true;
}
bool KeyValueParser::value(Slice * result){
    if(GetLengthPrefixedSlice(&bytes_, result) == false){
        return false;
    }
    return true;
}

bool KeyValueParser::keyValue(uint64_t * key, Slice * result){
    if(GetVarint64(&bytes_, key) == false){
        return false;
    }
    if(GetLengthPrefixedSlice(&bytes_, result) == false){
        return false;
    }
    return true;
}


void KeyValueBuilder::put(uint64_t key, const Slice & value){
    PutVarint64(&bytes_, key);
    PutLengthPrefixedSlice(&bytes_, value);
}
void KeyValueBuilder::clear(){
    bytes_.clear();
}
size_t KeyValueBuilder::approximateSize() const {
    return bytes_.size();
}
const std::string & KeyValueBuilder::contents() const {
    return bytes_;
}
static void appendHexTo(char c, std::ostringstream & oss) {
    static const char * hexTable = "0123456789ABCDEF";
    oss << hexTable[(c & 0xf0) >> 4]  << hexTable[c&0x0f];
}
const std::string KeyValueBuilder::toString() const {
    std::ostringstream oss;
    for(size_t i = 0; i < bytes_.size(); ++i){
        oss << "0x";
        appendHexTo(bytes_[i], oss);
        oss << " ";
    }
    return oss.str();
}
